package com.wyy.treeview.ui;

import java.util.ArrayList;
import java.util.List;

import com.wyy.treeview.core.DaoHelper;
import com.wyy.treeview.core.Location;
import com.wyy.treeview.R;
import com.wyy.treeview.R.id;
import com.wyy.treeview.R.layout;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

/**
 * 桥梁位置树结构
 * 
 * @author liu
 * 
 */
public class LocationFragment extends Fragment {
	private static final String ARG_POSITION = "position";

	private int position;
	private ListView lv_tree;
	// private OnLocSelectedListener mCallback;
	private String jsonData;
	private DaoHelper<Location> daoHelper;
	private List<Location> locations;
	private ArrayList<TreeElement> elements;
	private ArrayList<TreeElement> element0;
	private ArrayList<TreeElement> element1;
	private ArrayList<TreeElement> elementsData;
	private TreeViewAdapter treeViewAdapter;
	private View view;
	private ListView treeview;

	public static LocationFragment newInstance() {
		LocationFragment f = new LocationFragment();
		Bundle b = new Bundle();
		b.putInt(ARG_POSITION, 0);
		f.setArguments(b);
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		position = getArguments().getInt(ARG_POSITION);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_location, container, false);
		getLocData();//查询表数据、展现
		return view;
	}

	private void initView() {
		// LayoutInflater inflater = (LayoutInflater)
		// getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		treeview = (ListView) view.findViewById(R.id.treeview);
		treeViewAdapter = new TreeViewAdapter(getActivity(), elements,
				elementsData);
		treeview.setAdapter(treeViewAdapter);
		// treeview.setOnItemClickListener(treeViewItemClickListener);
		treeview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// 点击的item代表的元素
				TreeElement element = (TreeElement) treeViewAdapter
						.getItem(position);
				treeViewAdapter.setSelectedPosition(position);
				ArrayList<TreeElement> elements = treeViewAdapter.getElements();
				// 元素的数据源
				ArrayList<TreeElement> elementsData = treeViewAdapter
						.getElementsData();

				// 点击没有子项的item直接返回
				if (!element.isHasChildren()) {
					treeViewAdapter.notifyDataSetChanged();
					return;
				}

				if (element.isExpanded()) {	//展开状态时
					element.setExpanded(false);
					// 删除节点内部对应子节点数据，包括子节点的子节点...
					ArrayList<TreeElement> elementsToDel = new ArrayList<TreeElement>();
					for (int i = position + 1; i < elements.size(); i++) {
						if (element.getLevel() >= elements.get(i).getLevel())
							break;
						elementsToDel.add(elements.get(i));
					}
					elements.removeAll(elementsToDel);
					treeViewAdapter.notifyDataSetChanged();
				} else { //收缩状态时
					element.setExpanded(true);
					// 从数据源中提取子节点数据添加进树，注意这里只是添加了下一级子节点，为了简化逻辑
					int i = 1;// 注意这里的计数器放在for外面才能保证计数有效
					for (TreeElement e : elementsData) {
						if ((element.getId()).equals(e.getParendId())) {
							e.setExpanded(false);
							elements.add(position + i, e);
							i++;
						}
					}
					treeViewAdapter.notifyDataSetChanged();
				}
			}
		});
	}

	private TreeElement element;
	private boolean hasChildren = false;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				elements = new ArrayList<TreeElement>();
				element0 = new ArrayList<TreeElement>();
				element1 = new ArrayList<TreeElement>();
				elementsData = new ArrayList<TreeElement>();
				for (Location location : locations) {
					if ("Y".equalsIgnoreCase(location.getChildren())) {
						hasChildren = true;
					} else {
						hasChildren = false;
					}
					if (Integer.valueOf(location.getLevel()) == 0) { //根节点
						if (TextUtils.isEmpty(location.getParent())) {
							element = new TreeElement(
									location.getDescription(),
									Integer.valueOf(location.getLevel()),
									location.getUdrlevel(),
									location.getLocation(),
									TreeElement.NO_PARENT + "", true, true);
							element0.add(element);
						} else {
							// break;

						}

					} else if (Integer.valueOf(location.getLevel()) == 1) { //第二级
						TreeElement element = new TreeElement(
								location.getDescription(),
								Integer.valueOf(location.getLevel()),
								location.getUdrlevel(), location.getLocation(),
								location.getParent(), hasChildren, false);
						element1.add(element);
					}else { //二级以下
						element = new TreeElement(location.getDescription(),
								Integer.valueOf(location.getLevel()),
								location.getUdrlevel(), location.getLocation(),
								location.getParent(), hasChildren, true);
						elementsData.add(element);
					}
				}
				elements.addAll(element0);
				elements.addAll(element1);
				elementsData.addAll(element1);

				initView();
				break;
			}
		};
	};

	private void getLocData() {
		new Thread() {
			@Override
			public void run() {
				super.run();

				daoHelper = new DaoHelper<Location>(getActivity(),
						Location.class);
				locations = daoHelper.getQueryList(0, 0, null,
						"location_orderby");
				if (locations != null && locations.size() > 0) {
					handler.sendEmptyMessage(1);
				} else {
					handler.sendEmptyMessage(0);
				}
			};
		}.start();

	}

}
